package core

import (
	"google.golang.org/grpc"
	"log"
	"net"
	"report/global"
	"report/service"
	"report/service/grpc/report"
	"sync"
)

var grpcServer *grpc.Server
var grpcServerWG sync.WaitGroup

func InitGRPCServer() {
	// 创建 gRPC 服务器
	grpcServer = grpc.NewServer()
	report.RegisterReportServiceServer(grpcServer, &service.ReportServiceServer{})

	// 启动 gRPC 服务器
	grpcServerWG.Add(1)
	go func() {
		defer grpcServerWG.Done()
		addr := global.GVA_CONFIG.Grpc.Addr
		lis, err := net.Listen("tcp", ":"+addr)
		if err != nil {
			log.Fatalf("Failed to listen: %v", err)
		}
		log.Printf("gRPC server listening on :%s\n", addr)
		if err := grpcServer.Serve(lis); err != nil {
			log.Fatalf("Failed to serve gRPC server: %v", err)
		}
	}()
}

func ShutdownGRPCServer() {
	// 在程序结束时关闭 gRPC 服务器
	defer grpcServerWG.Wait()
	log.Println("Shutting down gRPC server")
	grpcServer.GracefulStop()
}
